package cn.zmwh.bbs.modules.bbs.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.zmwh.bbs.modules.bbs.pojo.entity.ForumBoard;
import cn.zmwh.bbs.modules.bbs.pojo.vo.ForumBoardNode;
import cn.zmwh.bbs.modules.bbs.service.ForumBoardService;
import cn.zmwh.common.core.api.Result;
import cn.zmwh.common.core.constants.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章板块信息 前端控制器
 * </p>
 *
 * @author dmzmwh
 * @since 2025-07-18
 */
@RestController
@RequestMapping("/bbs/board")
public class ForumBoardController {


    @Resource
    private ForumBoardService forumBoardService;

    @RequestMapping("/list")
    public Result<List<ForumBoardNode>> list(@ApiIgnore @RequestHeader(Constants.LANG_HEADER) String lang) {
        List<ForumBoard> list = forumBoardService.list(Wrappers.<ForumBoard>lambdaQuery()
                .orderByAsc(ForumBoard::getSort));
        List<ForumBoardNode> result = list.stream()
                .filter(menu -> menu.getPid().equals(0L))
                .map(menu -> covertMenuNode(menu, list,lang)).collect(Collectors.toList());
        return Result.ok(result);
    }

    private ForumBoardNode covertMenuNode(ForumBoard menu, List<ForumBoard> menuList,String lang) {
        ForumBoardNode node = new ForumBoardNode();
        BeanUtils.copyProperties(menu, node);
        String i18nJson = menu.getI18nJson();
        if (StrUtil.isNotBlank(i18nJson) && StrUtil.isNotBlank(lang)){
            JSONObject entries = JSONUtil.parseObj(i18nJson);
            String str = entries.getStr(lang);
            node.setBoardName(StrUtil.isNotBlank(str) ? str : menu.getBoardName());
        }
        List<ForumBoardNode> children = menuList.stream()
                .filter(subMenu -> subMenu.getPid().equals(menu.getId()))
                .map(subMenu -> covertMenuNode(subMenu, menuList,lang)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}

